package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.search.dtos.HistorySearchDTO;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.CustomAutowireConfigurer;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.validation.constraints.AssertFalse;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    BehaviorFeign behaviorFeign;
    @Autowired
    MongoTemplate mongoTemplate;

    @Async("taskExecutor")
    @Override
    public void insert(UserSearchDTO dto) {
        //1.获取当前用户
        //2. 根据登录用户id  或者这杯 id 查询行为实体  feign
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(dto.getUserId(), dto.getEquipmentId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApBehaviorEntry behaviorEntry = result.getData();
        //3.根据行为实体id 和 搜索关键词查询搜索历史记录
        ApUserSearch search = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("keyword").is(dto.getSearchWords())), ApUserSearch.class);

        //4.如果  已经有该记录  更新搜索时间
        if (search != null) {
            search.setCreatedTime(new Date());
            mongoTemplate.save(search);
        } else {
            search = new ApUserSearch();
            search.setCreatedTime(new Date());
            search.setEntryId(behaviorEntry.getId());
            search.setKeyword(dto.getSearchWords());
            mongoTemplate.save(search);
        }
        //5. 如果  没有该搜索记录   新增搜索记录
    }

    @Override
    public ResponseResult findUserSearch(UserSearchDTO dto) {
        //1.获取当前登录用户id
        ApUser user = AppThreadLocalUtils.getUser();

        //2. 根据用户id  或设备 id 查询行为实体
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApBehaviorEntry apBehaviorEntry = result.getData();
        //3.根据行为实体id   查询历史记录   按照创建时间降序 查询10条
        if (apBehaviorEntry!=null) {
            List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()))
                    .with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(10), ApUserSearch.class);
            //4.返回数据
            return ResponseResult.okResult(apUserSearches);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDTO dto) {
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> behaviorEntryResult = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if(!behaviorEntryResult.checkCode()){
            return ResponseResult.errorResult(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用行为服务失败");
        }
        ApBehaviorEntry behaviorEntry = behaviorEntryResult.getData();
        if(behaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体数据不存在");
        }
        mongoTemplate.remove(Query.query(Criteria.where("_id").is(dto.getId()).and("entryId").is(behaviorEntry.getId())),ApUserSearch.class);
        return ResponseResult.okResult();
    }
}
